<!-- 运费模板 -->
<template>
  <div class="freightTemp sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="模板名称:">
              <el-input v-model="query.transportName" placeholder="请输入模板名称" clearable/>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="运费模板数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table ref="table" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
          <el-table-column label="模板名称" prop="transportName" align="center"></el-table-column>
          <el-table-column label="是否包邮" prop="freeFeeFlag" align="center">
            <template #default="{row}">
              <span>{{ row.freeFeeFlag ? '包邮' : '不包邮' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.transportId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.transportId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.transportId ? '编辑' : '新增'" top="10vh" width="70%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="120px">
        <el-form-item label="模板名称:" prop="transportName" required>
          <el-input v-model="form.transportName" placeholder="请输入登录账号" clearable style="width: 215px;"/>
        </el-form-item>
        <el-form-item label="模板类型:" prop="freeFeeFlag">
          <el-radio-group v-model="form.freeFeeFlag">
            <el-radio :label="0">不包邮</el-radio>
            <el-radio :label="1">包邮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.freeFeeFlag === 0" label="收费方式:" prop="chargeType">
          <el-radio-group v-model="form.chargeType">
            <el-radio :label="0">按件数</el-radio>
            <el-radio :label="1">按重量</el-radio>
            <el-radio :label="2">按体积</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.freeFeeFlag === 0" label="收费区域:" prop="feeItemList" required>
          <el-button type="primary" icon="Plus" @click="doAddOrDelFeeItem(true)">添加收费区域</el-button>
          <el-table :data="form.feeItemList" border>
            <el-table-column label="配送区域" prop="feeCityList" align="center">
              <template #default="{row}">
                <div class="choose-regions">
                  <el-tag v-for="item in getChooseRegions(row.feeCityList)" :key="item.code">{{ item.name }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="首件/重量/体积" prop="firstPiece" align="center" width="160">
              <template #default="{row}">
                <el-input v-model="row.firstPiece" type="number" placeholder="请输入" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="首件运费" prop="firstFee" align="center" width="160">
              <template #default="{row}">
                <el-input v-model="row.firstFee" type="number" placeholder="请输入" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="续件/重量/体积数" prop="continuousPiece" align="center" width="160">
              <template #default="{row}">
                <el-input v-model="row.continuousPiece" type="number" placeholder="请输入" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="续费（元）" prop="continuousFee" align="center" width="160">
              <template #default="{row}">
                <el-input v-model="row.continuousFee" type="number" placeholder="请输入" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template #default="{$index}">
                <el-button type="primary" icon="MapLocation" link @click="toChooseRegion('feeCity', $index)">选择区域</el-button>
                <el-divider direction="vertical" />
                <el-button type="danger" icon="Delete" link @click="doAddOrDelFeeItem(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-if="form.freeFeeFlag === 1" label="包邮条件:" prop="hasFreeCondition">
          <el-radio-group v-model="form.hasFreeCondition">
            <el-radio :label="0">无包邮条件</el-radio>
            <el-radio :label="1">有包邮条件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.freeFeeFlag === 1 && form.hasFreeCondition === 1" label="指定包邮条件:" prop="feeFreeList" required>
          <el-button type="primary" icon="Plus" @click="doAddOrDelFeeFree(true)">添加包邮条件</el-button>
          <el-table :data="form.feeFreeList" border>
            <el-table-column label="配送区域" prop="deliveryCode" align="center">
              <template #default="{row}">
                <div class="choose-regions">
                  <el-tag v-for="item in getChooseRegions(row.freeCityList)" :key="item.code">{{ item.name }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="包邮条件" prop="freeType" align="center" width="240">
              <template #default="{row}">
                <el-radio-group v-model="row.freeType" @change="freeTypeChange(row)">
                  <el-radio :label="0">满件/重量/体积包邮</el-radio>
                  <el-radio :label="1">满金额包邮</el-radio>
                  <el-radio :label="2">满件/重量/体积且满金额包邮</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="条件值设定" align="center" width="200">
              <template #default="{row}">
                <div class="limit-box">
                  <div v-if="row.freeType === 0 || row.freeType === 2" class="set-limit">
                    <span>满</span>
                    <el-input  v-model="row.piece" type="number" size="small" clearable></el-input>
                    <span>件/重量/体积</span>
                  </div>
                  <div v-if="row.freeType === 1 || row.freeType === 2" class="set-limit">
                    <span>满</span>
                    <el-input v-model="row.amount" type="number" size="small" clearable></el-input>
                    <span>金额包邮</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template #default="{$index}">
                <el-button type="primary" icon="MapLocation" link @click="toChooseRegion('freeCity', $index)">选择区域</el-button>
                <el-divider direction="vertical" />
                <el-button type="danger" icon="Delete" link @click="doAddOrDelFeeFree(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="不送达区域:" prop="unableCityFlag">
          <el-radio-group v-model="form.unableCityFlag">
            <el-radio :label="0">不指定</el-radio>
            <el-radio :label="1">指定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.unableCityFlag === 1" prop="unableCityCodeList" required>
          <el-button type="primary" icon="Plus" @click="toChooseRegion('unableCityCode')">添加指定区域</el-button>
          <div class="unableCityCode">
            <div v-if="form.unableCityCodeList.length" class="data-box">
              <el-tag v-for="item in getChooseRegions(form.unableCityCodeList)" :key="item.code">{{ item.name }}</el-tag>
            </div>
            <div v-else class="empty-data">暂无数据</div>
          </div>
        </el-form-item>
      </el-form>
      <el-dialog class="append-to-body-dialog" v-model="innerShow" title="选择区域" top="5vh" width="70%" center draggable append-to-body>
        <el-tree
          ref="treeRef"
          node-key="code"
          show-checkbox 
          default-expand-all
          :data="regions"
          :props="{label: 'name'}"/>
        <template #footer>
          <el-button type="primary" size="default" @click="doChooseRegion">选择</el-button>
          <el-button size="default" @click="innerShow = false">关闭</el-button>
        </template>
      </el-dialog>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="freightTemp">
  import { cudFreightTempApi, getFreightTempListPagesApi, getFreightTempInfoApi, getRegionCityApi } from '@/api/api'
  import { arrTreeToArr } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated, nextTick } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  // 获取form表单的ref
  const formRef = ref(null)
  const treeRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    innerShow: false,
    arrIndex: 0,
    treeType: '',
    query: {
      transportName: '',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    regions: [],
    form: {
      transportId: '',
      transportName: '',
      freeFeeFlag: 0,
      hasFreeCondition: 0,
      chargeType: 0,
      unableCityFlag: 0,
      feeItemList: [],
      feeFreeList: [],
      unableCityCodeList: []
    },
    rules: {
      transportName: [{ required: true, message: '请输入模板名称', trigger: ['blur', 'change'] }],
      feeItemList: [{ 
        required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
          if(!value.length) {
            callback(new Error('请添加收费区域'))
          } else {
            for (let i = 0; i < value.length; i++) {
              if(value[i].feeCityList.length === 0) {
                callback(new Error('请选择配送区域'))
              }
              if(!value[i].firstPiece) {
                callback(new Error('请输入首件/重量/体积'))
              }
              if(!value[i].firstFee) {
                callback(new Error('请输入首件运费'))
              }
              if(!value[i].continuousPiece) {
                callback(new Error('请输入续件/重量/体积数'))
              }
              if(!value[i].continuousFee) {
                callback(new Error('请输入续费（元）'))
              }
              if(i === (value.length - 1)) {
                callback()
              }
            }
          }
        } 
      }],
      feeFreeList: [{ 
        required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
          if(!value.length) {
            callback(new Error('请添加包邮条件'))
          } else {
            for (let i = 0; i < value.length; i++) {
              if(value[i].freeCityList.length === 0) {
                callback(new Error('请选择配送区域'))
              }
              if((value[i].freeType === 0 || value[i].freeType === 2) && !value[i].piece) {
                callback(new Error('请输入条件值设定'))
              }
              if((value[i].freeType === 1 || value[i].freeType === 2) && !value[i].amount) {
                callback(new Error('请输入条件值设定'))
              }
              if(i === (value.length - 1)) {
                callback()
              }
            }
          }
        } 
      }],
      unableCityCodeList: [{ required: true, message: '请添加不送达区域', trigger: ['blur', 'change'] }],
    }
  })
  let {loading, show, innerShow, arrIndex, treeType, query, dataList, regions, defaultProps, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getFreightTempListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function initCitys() {
    getRegionCityApi().then(res => {
      if(res.code === '200') {
        currentData.regions = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑 feeItemList feeFreeList unableCityCodeList
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.transportId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.transportId ? '修改' : '新增'}`)
          if(currentData.form.freeFeeFlag === 0) { // 不包邮
            currentData.form.feeFreeList = []
          }
          if(currentData.form.freeFeeFlag === 1) { // 包邮
            currentData.form.feeItemList = []
          }
          if(currentData.form.freeFeeFlag === 1 && currentData.form.hasFreeCondition === 0) { // 包邮且有无包邮条件
            currentData.form.feeFreeList = []
          }
          if(currentData.form.unableCityFlag === 0) { // 指定不送达区域-不指定
            currentData.form.unableCityCodeList = []
          }
          cudFreightTempApi(`${currentData.form.transportId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              load(currentData.form.transportId ? currentData.query.current : 1)
              currentData.show = false
              currentThis.$message.success(res.message)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改查询详情，弹窗
  function toUpdate(transportId) {
    getFreightTempInfoApi(transportId).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.show = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 删除
  function doDelete(transportId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      cudFreightTempApi('delete', { id: transportId }).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 添加或删除收费区域
  function doAddOrDelFeeItem(type, index) {
    if(type) {
      currentData.form.feeItemList.push({feeCityList: [], firstFee: '', firstPiece: '', continuousPiece: '', continuousFee: ''})
    } else {
      currentData.form.feeItemList.splice(index, 1)
    }
  }

  // 添加或删除包邮条件
  function doAddOrDelFeeFree(type, index) {
    if(type) {
      currentData.form.feeFreeList.push({freeCityList: [], freeType: 0, piece: '', amount: ''})
    } else {
      currentData.form.feeFreeList.splice(index, 1)
    }
  }

  // 选择区域弹窗
  function toChooseRegion(type, index) {
    currentData.arrIndex = index
    currentData.treeType = type
    currentData.innerShow = true
    // 设置默认地区选择
    nextTick(() => {
      switch (type) {
        case 'feeCity': // 不包邮情况
          treeRef.value.setCheckedKeys(currentData.form.feeItemList[index].feeCityList)
          break
        case 'freeCity': // 包邮且有包邮条件
          treeRef.value.setCheckedKeys(currentData.form.feeFreeList[index].freeCityList)
          break
        case 'unableCityCode': // 指定不送达区域
          treeRef.value.setCheckedKeys(currentData.form.unableCityCodeList)
          break
        default:
          break
      }
    })
  }

  function doChooseRegion() {
    let trees = treeRef.value.getCheckedKeys(true)
    if(!trees.length) {
      currentThis.$message.error('请选择区域')
      return
    }
    switch (currentData.treeType) {
      case 'feeCity': // 不包邮情况
        currentData.form.feeItemList[currentData.arrIndex].feeCityList = trees
        break
      case 'freeCity': // 包邮且有包邮条件
        currentData.form.feeFreeList[currentData.arrIndex].freeCityList = trees
        break
      case 'unableCityCode': // 指定不送达区域
        currentData.form.unableCityCodeList = trees
        break
      default:
        break
    }
    currentData.innerShow = false
  }

  // 根据所选区域获取区域名称信息等
  function getChooseRegions(arr) {
    let list = []
    const regionList = arrTreeToArr(currentData.regions, 'children')
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < regionList.length; j++) {
        if(regionList[j].code === arr[i]) {
          list.push(regionList[j])
          break
        }
      }
    }
    return list
  }

  // 模板类型：包邮， 包邮条件：有包邮条件时候，表格中的包邮条件单选按钮点击时候执行
  function freeTypeChange(e) {
    e.piece = ''
    e.amount = ''
  }

  // 重置查询
  function resetSearch() {
    currentData.query.transportName = ''
    load(1)
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      transportId: '',
      transportName: '',
      freeFeeFlag: 0,
      hasFreeCondition: 0,
      chargeType: 0,
      unableCityFlag: 0,
      feeItemList: [],
      feeFreeList: [],
      unableCityCodeList: []
    }
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
    initCitys()
  })
</script>

<style lang="less" scoped>
.freightTemp{
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
    }
    .el-table{
      margin-top: 10px;
      .limit-box{
        height: 60px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .set-limit{
          display: flex;
          align-items: center;
          .el-input{
            width: 60px;
            margin: 0 5px;
          }
        }
      }
      .choose-regions{
        display: flex;
        flex-wrap: wrap;
        .el-tag{
          margin: 0 3px 3px 0;
        }
      }
    }
    .unableCityCode{
      width: calc(100% - 20px);
      margin-top: 10px;
      padding: 10px 10px;
      border: #ebeef5 solid 1px;
      >.data-box{
        width: 100%;
        .el-tag{
          margin-right: 3px;
        }
      }
      >.empty-data{
        width: 100%;
        text-align: center;
        color: #909399;
      }
    }
  }
}
</style>